import os
from wsgiref.simple_server import make_server
import simpleweb.utils


def wsgiserve(wsgiapp, host='127.0.0.1', port=8080, reload=True, user='nobody', group='nobody', infomsg=None, warnmsg=None):
    if reload:
        reload_status = 'On'
    else:
        reload_status = 'Off'

    server = make_server(host, port, wsgiapp)

    if os.name == 'posix':
        import pwd, grp

        if os.geteuid() == 0: #only do this if we're root
            try:
                gid = grp.getgrnam(group)[2]
                uid = pwd.getpwnam(user)[3]
            except KeyError:
                simpleweb.utils.msg_err("Could not find the specified user/group on the system, ignoring and running as '%s'" %(pwd.getpwuid(os.geteuid())[0]))
                pass
            else:
                if os.name == 'posix':
                    os.setgid(gid)
                    os.setuid(uid)

    simpleweb.utils.msg_info("simpleweb.webserver - v0.2")
    simpleweb.utils.msg_info("Based on wsgiref.simple_server")

    if infomsg:
        simpleweb.utils.msg_info(infomsg)

    if warnmsg:
        simpleweb.utils.msg_warn(warnmsg)

    simpleweb.utils.msg_info("Now Serving on %s port %s [reloading = %s]..." % (host, port, reload_status))
    server.serve_forever()
